var form, cropper;
var options = {
    aspectRatio: 1, // 裁剪框比例
    preview: '#previewImage', // 预览div
    viewmode: 1
};

$(function () {
    initLayUI(function () {
        initButtons();
    });
});

function initLayUI(cb) {
    layui.use(['cropper', 'form'], function () {
        cropper = layui.cropper;
        form = layui.form;

        let userInfo = getTempData('userInfo');
        $("#sourceImage").attr("src", userInfo.avatar);
        $("#sourceImage").cropper(options);

        form.on('submit(profileForm)', function (data) {
            $("#sourceImage").crossOrigin = 'anonymous';//解决跨域图片问题
            $("#sourceImage").cropper("getCroppedCanvas", {
                width: 280,
                height: 140
            }).toBlob(function (blob) {
                var timeStamp = Date.parse(new Date());
                var fileName = timeStamp + '.jpg';
                var formData = new FormData();
                formData.append('file', blob, fileName);
                formData.append('fileName', fileName);
                formData.append('fileToken', timeStamp);

                var reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onload = function (e) {
                    uploadAvatar(e.target.result);
                };
            });
        });

        cb();
    });
}

function initButtons() {
    $(".pear-btn").on('click', function () {
        var event = $(this).attr("cropper-event");

        if (event === 'rotate') {
            var option = $(this).attr('data-option');
            $("#sourceImage").cropper('rotate', option);
        } else if (event === 'reset') {
            $("#sourceImage").cropper('reset');
        }

        $("#uploadPicture").change(function () {
            var r = new FileReader();
            var f = this.files[0];

            var uploadFileSize = f.size / 1024;
            if (uploadFileSize > 1024) {
                parent.layer.msg("上传文件不得超过1m", {icon: 5});
                return false;
            }

            r.readAsDataURL(f);
            r.onload = function (e) {
                $("#sourceImage")
                    .cropper('destroy')
                    .attr('src', this.result)
                    .cropper(options);
            };
        });
    });

    $("#cancelBtn").click(function () {
        layerUtil.closeLayer(parent.window.iframeIndex);
    });
}

function uploadAvatar(avatar) {
    ajaxUtil.simplePost({avatar: avatar}, "/user/updateAvatar", function (data) {
        layerUtil.closeLayer();
        execParentFunction('userAvatar', "reloadParentAvatar('" + data + "')");
    });
}